package com.mdd.controller;

import com.mdd.domain.Result;
import com.mdd.domain.User;
import com.mdd.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

// 使用 REST风格简化代码
@RestController
@RequestMapping("users")
public class userController {

    @Autowired
    private UserService userService;

    //  查询所有用户
    @GetMapping
    public Result selectAll(){
        List<User> users = userService.selectAll();
        System.out.println("selectAll is ok...");
        return Result.success(200,"查询成功",users);
    }

    // 新增用户
    @PostMapping
    public Result addUser(@RequestBody User user){
        Integer num = userService.addUser(user);
        System.out.println("user add is ok...");
        if(num > 0) return Result.success(200,"新增成功");
        return Result.failure(404,"新增失败");
    }

    // 根据id查询用户
    @GetMapping("/{id}")
    // @PathVariable 绑定路径参数
    public Result selectById(@PathVariable Integer id){
        System.out.println("selectById is ok...");
        User user = userService.selectById(id);
        if(user != null) return Result.success(200,"查询成功",user);
        return Result.failure(404,"查无此人");
    }

    // 根据id修改用户
    @PutMapping
    // @PathVariable 绑定路径参数
    public Result updateById(@RequestBody User user){
        Integer num = userService.updateById(user);
        System.out.println("updateById is ok...");
        if(num > 0 ) return Result.success(200,"修改成功");
        return Result.failure(404,"修改失败");
    }

    // 根据id删除用户
    @DeleteMapping("/{id}")
    // @PathVariable 绑定路径参数
    public Result deleteById(@PathVariable Integer id){
        Integer num = userService.deleteById(id);
        System.out.println("deleteById is ok...");
        if(num > 0 ) return Result.success(200,"删除成功");
        return Result.failure(404,"删除失败");
    }


}
